package com.wlc.service.impl;

import com.wlc.mapper.ResignationMapper;
import com.wlc.pojo.Resignation;
import com.wlc.pojo.ResignationStats;
import com.wlc.service.ResignationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ResignationServiceImpl implements ResignationService {

    @Autowired
    private ResignationMapper resignationMapper;

    @Override
    public Resignation findById(Long id) {
        log.info("根据ID查询辞职申请: {}", id);
        return resignationMapper.selectById(id);
    }

    @Override
    public List<Resignation> findList(Resignation resignation) {
        log.info("查询辞职申请列表");
        return resignationMapper.selectList(resignation);
    }

    @Override
    @Transactional
    public void save(Resignation resignation) {
        log.info("新增辞职申请: employeeId={}", resignation.getEmployeeId());

        // 检查员工是否已存在待处理的辞职申请
        boolean existsPending = resignationMapper.existsPendingResignation(resignation.getEmployeeId());
        if (existsPending) {
            throw new RuntimeException("该员工已存在待处理的辞职申请");
        }

        // 设置默认值
        resignation.setStatus(1); // 待审批
        resignation.setIsDeleted(0);
        resignation.setCreateTime(LocalDateTime.now());
        resignation.setUpdateTime(LocalDateTime.now());

        if (resignation.getApplyDate() == null) {
            resignation.setApplyDate(LocalDate.now());
        }

        int result = resignationMapper.insert(resignation);
        if (result <= 0) {
            throw new RuntimeException("新增辞职申请失败");
        }

        log.info("新增辞职申请成功: id={}", resignation.getId());
    }

    @Override
    @Transactional
    public void update(Resignation resignation) {
        log.info("更新辞职申请: {}", resignation.getId());

        Resignation existingResignation = resignationMapper.selectById(resignation.getId());
        if (existingResignation == null) {
            throw new RuntimeException("辞职申请不存在");
        }

        // 只能修改待审批状态的申请
        if (existingResignation.getStatus() != 1) {
            throw new RuntimeException("只能修改待审批状态的辞职申请");
        }

        resignation.setUpdateTime(LocalDateTime.now());
        int result = resignationMapper.update(resignation);
        if (result <= 0) {
            throw new RuntimeException("更新辞职申请失败");
        }

        log.info("更新辞职申请成功: {}", resignation.getId());
    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        log.info("删除辞职申请: {}", id);

        Resignation resignation = resignationMapper.selectById(id);
        if (resignation == null) {
            throw new RuntimeException("辞职申请不存在");
        }

        // 只能删除待审批状态的申请
        if (resignation.getStatus() != 1) {
            throw new RuntimeException("只能删除待审批状态的辞职申请");
        }

        int result = resignationMapper.deleteById(id);
        if (result <= 0) {
            throw new RuntimeException("删除辞职申请失败");
        }

        log.info("删除辞职申请成功: {}", id);
    }

    @Override
    @Transactional
    public void approveResignation(Long id, Long approverId, String approvalOpinion) {
        log.info("批准辞职申请: id={}, approverId={}", id, approverId);

        Resignation resignation = resignationMapper.selectById(id);
        if (resignation == null) {
            throw new RuntimeException("辞职申请不存在");
        }

        if (resignation.getStatus() != 1) {
            throw new RuntimeException("只能审批待审批状态的辞职申请");
        }

        int result = resignationMapper.approveResignation(id, approverId, approvalOpinion);
        if (result <= 0) {
            throw new RuntimeException("批准辞职申请失败");
        }

        // 这里可以添加后续逻辑，如更新员工状态为离职等
        log.info("批准辞职申请成功: {}", id);
    }

    @Override
    @Transactional
    public void rejectResignation(Long id, Long approverId, String approvalOpinion) {
        log.info("拒绝辞职申请: id={}, approverId={}", id, approverId);

        Resignation resignation = resignationMapper.selectById(id);
        if (resignation == null) {
            throw new RuntimeException("辞职申请不存在");
        }

        if (resignation.getStatus() != 1) {
            throw new RuntimeException("只能审批待审批状态的辞职申请");
        }

        int result = resignationMapper.rejectResignation(id, approverId, approvalOpinion);
        if (result <= 0) {
            throw new RuntimeException("拒绝辞职申请失败");
        }

        log.info("拒绝辞职申请成功: {}", id);
    }

    @Override
    @Transactional
    public void cancelResignation(Long id) {
        log.info("取消辞职申请: {}", id);

        Resignation resignation = resignationMapper.selectById(id);
        if (resignation == null) {
            throw new RuntimeException("辞职申请不存在");
        }

        // 只能取消待审批状态的申请
        if (resignation.getStatus() != 1) {
            throw new RuntimeException("只能取消待审批状态的辞职申请");
        }

        int result = resignationMapper.updateStatus(id, 4); // 已取消
        if (result <= 0) {
            throw new RuntimeException("取消辞职申请失败");
        }

        log.info("取消辞职申请成功: {}", id);
    }

    @Override
    public List<ResignationStats> getDeptResignationStats(String year) {
        log.info("查询部门辞职统计: year={}", year);
        if (year == null || year.trim().isEmpty()) {
            year = String.valueOf(LocalDate.now().getYear());
        }
        return resignationMapper.selectDeptResignationStats(year);
    }

    @Override
    public List<ResignationStats> getMonthlyResignationTrend(String year) {
        log.info("查询月度辞职趋势: year={}", year);
        if (year == null || year.trim().isEmpty()) {
            year = String.valueOf(LocalDate.now().getYear());
        }
        return resignationMapper.selectMonthlyResignationTrend(year);
    }

    @Override
    public List<ResignationStats> getResignReasonStats(String year) {
        log.info("查询辞职原因统计: year={}", year);
        if (year == null || year.trim().isEmpty()) {
            year = String.valueOf(LocalDate.now().getYear());
        }
        return resignationMapper.selectResignReasonStats(year);
    }

    @Override
    public List<ResignationStats> getResignationStatusStats(String year) {
        log.info("查询辞职状态统计: year={}", year);
        if (year == null || year.trim().isEmpty()) {
            year = String.valueOf(LocalDate.now().getYear());
        }
        return resignationMapper.selectResignationStatusStats(year);
    }

    @Override
    public ResignationStats getResignationSummary(String year) {
        log.info("查询辞职汇总统计: year={}", year);
        if (year == null || year.trim().isEmpty()) {
            year = String.valueOf(LocalDate.now().getYear());
        }
        return resignationMapper.selectResignationSummary(year);
    }

    @Override
    public Object getResignationOverview(String year) {
        log.info("查询辞职统计总览: year={}", year);
        if (year == null || year.trim().isEmpty()) {
            year = String.valueOf(LocalDate.now().getYear());
        }

        Map<String, Object> result = new HashMap<>();
        result.put("deptStats", getDeptResignationStats(year));
        result.put("monthlyTrend", getMonthlyResignationTrend(year));
        result.put("reasonStats", getResignReasonStats(year));
        result.put("statusStats", getResignationStatusStats(year));
        result.put("summary", getResignationSummary(year));

        return result;
    }
}